# -*- coding: utf-8 -*-
"""
Created on Wed Sep 04 12:35:53 2013

@author: Administrator
"""
import serial
import numpy as np
import time

class HighVoltageDevice:
    def __init__(self, name, COM):
        self.name = name
        self.COM = COM  # COM port number, python will use COM-1

        # things to be set    
        self.serial = None
        self.waitTime = 0.05
    
    def Connect(self):
        try:
            self.serial = serial.Serial(port=self.COM-1,baudrate=9600,\
                bytesize=serial.EIGHTBITS,parity=serial.PARITY_NONE,\
                stopbits=serial.STOPBITS_ONE, timeout=0.5)
        except:
            print('Could not connect to COM' %(self.COM))
    def Disconnect(self):
        if self.serial != None:
            self.serial.close()
    def ReadVoltages(self, *arg):
        """ Returns set voltages, measured voltages, currents"""
        
        if arg == ():
            channelList = np.arange(1,200)
        else:
            channelList = arg[0]
        
        # Make containers
        voltagesMeasured = np.zeros(200)
        currentsMeasured = np.zeros(200)
        voltagesSet = np.zeros(200)
        voltagesPreset = np.zeros(200)
        
        self.serial.flush()
        i = 0
        for ch in channelList:
            # get measured voltage
            cmmd = ('%0.3X' % (ch))  + 'r1\r'
            self.serial.write(cmmd)
            
            time.sleep(self.waitTime)
            lineIn = self.serial.read(9)
            # break if no more channels
#            print lineIn
            if (lineIn == ''):
                break
            voltagesMeasured[i] = int(lineIn[-4:-1], 16)/2.0
        
            # get measured current
            cmmd = ('%0.3X' % (ch))  + 'r2\r'
            self.serial.write(cmmd)
            time.sleep(self.waitTime)
            lineIn = self.serial.read(9)
            currentsMeasured[i] = int(lineIn[-4:-1], 16)
        
            # get set voltage
            cmmd = ('%0.3X' % (ch))  + 'v\r'
            self.serial.write(cmmd)
            time.sleep(self.waitTime)
            lineIn = self.serial.read(8)
            voltagesSet[i] = int(lineIn[-4:-1], 16)/2.0

            # get preset voltage register 0 (there are 7 registers)
            cmmd = ('%0.3X' % (ch))  + 'vp0\r'
            self.serial.write(cmmd)
            time.sleep(self.waitTime)
            lineIn = self.serial.read(9)
            voltagesPreset[i] = int(lineIn[-4:-1], 16)/2.0
            i +=1

            
#            print('%d\t%3.2f\t%3.2f\t%3.2f' %(ch,voltagesSet[i], voltagesMeasured[i], currentsMeasured[i]))

        voltagesMeasured = voltagesMeasured[0:i]
        currentsMeasured = currentsMeasured[0:i]
        voltagesSet = voltagesSet[0:i]
        voltagesPreset = voltagesPreset[0:i]
        return(voltagesMeasured, voltagesSet, voltagesPreset, currentsMeasured)
        
    def SetVoltages(self, channelList, voltageList):
        """ Change voltage"""
        MAXVOLTAGE = 1200
        for (i, ch) in enumerate(channelList):
            # set measured voltage
            if voltageList[i] <= MAXVOLTAGE:
                cmmd = ('%0.3X' % (ch)) + 'V' + ('%0.3X' % (voltageList[i]*2)  )  +  '\r'
    #            print cmmd
                self.serial.write(cmmd)            
                time.sleep(self.waitTime)
                lineIn = self.serial.read(8)
                print('%d\t%3.2f' %(ch,int(lineIn[-4:-1], 16)/2.0) )
            else:
                print("Channel %d: Voltage setting is too high. Voltage not set." %ch)

    def IncrementVoltages(self, channelList, voltageIncrementList):
        """ Increment voltage"""
        # clunky way to see if array
        try:
            voltageIncrementList[1]
            # convert numpy in case its a list or somethine else
            voltageIncrementList = np.array(voltageIncrementList)
        except:
            # if not array then make an array
            voltageIncrementList = np.ones(len(channelList)) * voltageIncrementList
        # get measured voltage, set voltage, current
        (vm, vs, vp, c) = self.ReadVoltages(channelList)
        newVoltages = voltageIncrementList + vs
        cut = newVoltages < 0
        newVoltages[cut] = 0
#        print("measured voltages")
#        print vm
#        print("new voltages")
#        print newVoltages
        self.SetVoltages(channelList, newVoltages)
        
    def SetToPreset(self,channelList):
        """Sets to preset values"""
        
        